package com.sh.rbac.core.security.service;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sh.rbac.core.common.enums.UserTypeEnum;
import com.sh.rbac.core.common.util.IpAddressUtils;
import com.sh.rbac.core.common.util.WebUtils;
import com.sh.rbac.core.security.entity.LoginUser;
import com.sh.rbac.domain.entity.User;
import com.sh.rbac.domain.vo.dept.DeptVO;
import com.sh.rbac.mapper.DeptMapper;
import com.sh.rbac.mapper.MenuMapper;
import com.sh.rbac.mapper.RoleMapper;
import com.sh.rbac.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
 * @since 2024-04-07 14:16
 */

@Service
public class LoginService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) {

        // 根据用户名查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(username != null, User::getUsername, username));

        // 判断用户是否存在
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 判断用户类型
        Long userId = UserTypeEnum.isAdmin(user.getUsertype()) ? null : user.getId();

        //添加用户部门
        DeptVO dept = deptMapper.selectDeptById(user.getDeptId());
        if(dept != null) {
            user.setDeptName(dept.getName());
        }

        // 添加用户角色
        user.setRoles(new HashSet<>(roleMapper.getRolesByUserId(userId)));

        // 添加用户登录信息
        HttpServletRequest request = WebUtils.getRequest();
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));

        user.setBrowser(userAgent.getBrowser() + " " + userAgent.getVersion());
        user.setOs(userAgent.getOs().getName() + " " + userAgent.getOsVersion());
        user.setLoginIp(IpAddressUtils.getIpAddress(request));
        user.setLoginLocation(IpAddressUtils.getCityInfoByVectorIndex(user.getLoginIp()));
        user.setLoginTime(LocalDateTime.now());


        // 获取用户权限
        if(UserTypeEnum.isAdmin(user.getUsertype())){
            user.setPermissions(Set.of("*:*:*"));
        }else{
            // 添加用户权限列表
            Set<String> permissions = new HashSet<>(menuMapper.getPermissionByUserId(userId));
            user.setPermissions(permissions);
        }

        // 返回用户详情
        return new LoginUser(user);
    }
}
